<template>
<!-- 角色列表组件 -->
<div>
    <el-breadcrumb separator-class="el-icon-arrow-right">
        <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
        <el-breadcrumb-item>权限管理</el-breadcrumb-item>
        <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片视图 -->
    <el-card>
        <el-button type="primary" @click="DialogRloeVisible = true">添加角色</el-button>
        <user-table :RloesList="RloesList" @NewRloesList="NewList"></user-table>
    </el-card>
    <!-- 添加角色弹出框 -->
    <el-dialog title="添加角色" :visible.sync="DialogRloeVisible" @close="addRloesClosed" width="50%">
      <el-form :model="addRloesForm" label-width="90px" ref="addRloesRef" :rules="addRloesRules">
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="addRloesForm.roleName"></el-input>
        </el-form-item>
        <el-form-item label="角色描述" prop="roleDesc">
          <el-input v-model="addRloesForm.roleDesc"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="DialogRloeVisible = false">取 消</el-button>
        <el-button type="primary" @click="addRloe">确 定</el-button>
      </div>
    </el-dialog>
</div>
</template>
<script>
import userTable from './children/RloesTable'
export default {
  components: {
    userTable
  },
  data () {
    return {
      // 接收添加角色的数据
      addRloesForm: {
        roleName: '',
        roleDesc: ''
      },
      // 控制角色框显示关闭状态
      DialogRloeVisible: false,
      // 所有角色数据
      RloesList: [],
      // 添加表单效验规则
      addRloesRules: {
        roleName: [
          { required: true, message: '角色名不能为空!', trigger: 'blur' },
          { min: 4, max: 10, message: '用户名的长度在4~10个字符之间!', trigger: 'blur' }
        ],
        roleDesc: [
          { required: true, message: '角色描述不能为空!', trigger: 'blur' },
          { min: 4, max: 10, message: '用户名的长度在4~10个字符之间!', trigger: 'blur' }
        ]
      }
    }
  },
  created () {
    this.getRloesList()
  },
  methods: {
    // 点击确定添加角色
    addRloe () {
      // validate 对整个表单进行校验
      this.$refs.addRloesRef.validate(async valid => {
        if (!valid) return
        const { data: res } = await this.$http.post('roles', this.addRloesForm)
        if (res.meta.status !== 201) return this.$message.error('添加角色失败')
        this.$message.success(res.meta.msg)
        // 隐藏添加用户的对话框
        this.DialogRloeVisible = false
        // 重新获取数据
        this.getRloesList()
      })
    },
    // 关闭的回调
    addRloesClosed () {
      this.$refs.addRloesRef.resetFields()
    },
    // 角色权限修改成功后重新渲染数据
    NewList () {
      this.getRloesList()
    },
    // 角色列表数据请求
    async getRloesList () {
      const { data: res } = await this.$http.get('roles')
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg || '角色列表数据获取失败')
      this.RloesList = res.data
    }
  }
}
</script>
